﻿using System;
using System.Net;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using NLSCAN.MacCtrl;
using ScannerKey;
using System.Runtime.InteropServices;

namespace Scan
{  
    public partial class frmWl : Form
    {
        private OperationClass _operationClass;
        Thread DataThread = null;
        private flManage.WlManger wlmanger = null;
        private bool IsXiang = false;
        private bool IsDan = false;
        private Scan scan;
        private NLSScanner scanTest;
        private ScanKey scanner2D = null;
        private ScannerMsgOne ScannerReader;
        private CustomMessageHandler cmh;
        private bool isThreadRun = false;
        private List<string> allwlcode = null;
        private bool listBoxFocus = false;
        private bool textBoxFocus = false;


        private bool formOpenFlag = false;

        private bool isCanScanner = false;

        bool isGetMessage = false;

        ThreadStart threadStart = null;
        Thread thread = null;

        /// <summary>
        /// 错误日志文件的路径
        /// </summary>
        private string filepath = "";
        /// <summary>
        /// 执行出入库操作的物流码的总个数
        /// </summary>
        private int truesum = 0;
        /// <summary>
        /// 执行出入库操作发生错误的总个数
        /// </summary>
        private int falsesum = 0;
        /// <summary>
        /// 截止到当前时点共成功写进错误日志的总个数
        /// </summary>
        private int ingwritesum = 0;
        private List<string> log = new List<string>();
        private string smsJxsid = "";

        private delegate void UIDelegateMethod(string str);
        private delegate void UIDelegateMethodLabel4(string str);
        private delegate void UIDelegateMethodListBox(int i);
        private delegate void UIDelegateMethodAddtextBox3(string str);
        private delegate void UIDelegateMethodAddListBox(string str);

        #region 扫描条码相关程序

        private void scanner2D_OnScannerUp(object sender, EventArgs e)
        {
            isCanScanner = false;
            isGetMessage = false;
        }

        private void scanner2D_OnScannerDown(object sender, EventArgs e)
        {
            formOpenFlag = true;
            isCanScanner = true;
        }

        private void DoWork()
        {
            ScannerMsg.ResCode resCode;

            ScannerMsg.DecodeMessage decodeMessage = new ScannerMsg.DecodeMessage();

            decodeMessage.message = new Char[1024];
            decodeMessage.codeID = new Char[256];
            decodeMessage.symLetter = new Char[256];
            decodeMessage.symModifer = new Char[256];
            decodeMessage.length = 1024;

            while (formOpenFlag)
            {
                Thread.Sleep(100);

                while (isCanScanner)
                {
                    Thread.Sleep(20);

                    if (isGetMessage)
                    {
                        break;
                    }

                    resCode = ScannerMsg.oemWaitForDecode(1, decodeMessage.message, decodeMessage.codeID, decodeMessage.symLetter, decodeMessage.symModifer, ref decodeMessage.length, null);

                    if (resCode == ScannerMsg.ResCode.RESULT_ERR_NODECODE)
                    {
                        continue;
                    }
                    else if (resCode == ScannerMsg.ResCode.RESULT_ERR_NOTRIGGER)
                    {
                        break;
                    }
                    else if (resCode == ScannerMsg.ResCode.RESULT_SUCCESS)
                    {
                        String msg = new String(decodeMessage.message);

                        try
                        {
                            AppendMessage(msg.Trim());
                           // Sound.PlaySoundFile(@"\\windows\\beeph.wav");
                            Sound.Beep();
                            isGetMessage = true;
                        }
                        catch (System.Exception e)
                        {

                        }

                        break;
                    }
                }
            }
        }

        delegate void DelegateFun(String message);

        private void AppendMessage(String message)
        {
            if (listBoxFocus)
            {
                if (message.Length >= 12)
                {
                    if (PublicVar.IsCheckDistinct) //检查扫描的是否有重复值
                    {
                        allwlcode.Add(message);
                        foreach (string atm in allwlcode)
                        {
                            if (string.Equals(atm, message))
                            {
                                MessageBox.Show(string.Format("{0}物流码已被扫描处理过，请谨慎操作！", message));
                                break;
                            }
                        }
                    }

                    AddListBox(message);
                }
            }

            if (textBoxFocus)
            {
                AddtextBox3(message);
            }

        }

        private void MovFormControl()
        {
            listBox1.Location = new Point(listBox1.Location.X, listBox1.Location.Y + 20);
            radioButton1.Location = new Point(radioButton1.Location.X, radioButton1.Location.Y + 20);
            radioButton2.Location = new Point(radioButton2.Location.X, radioButton2.Location.Y + 20);
            
            textBox2.Location = new Point(textBox2.Location.X, textBox2.Location.Y + 20);
            textBox1.Location = new Point(textBox1.Location.X, textBox1.Location.Y + 20);
            textBox4.Location = new Point(textBox4.Location.X, textBox4.Location.Y + 20);
            textBox3.Location = new Point(textBox3.Location.X, textBox3.Location.Y + 20);
            label1.Location = new Point(label1.Location.X, label1.Location.Y + 20);
            label2.Location = new Point(label2.Location.X, label2.Location.Y + 20);
            label3.Location = new Point(label3.Location.X, label3.Location.Y + 20);
            label4.Location = new Point(label4.Location.X, label4.Location.Y + 20);
            label5.Location = new Point(label5.Location.X, label5.Location.Y + 20);
            label6.Location = new Point(label6.Location.X, label6.Location.Y + 20);
            label7.Location = new Point(label7.Location.X, label7.Location.Y + 20);
        }

        private void InitScan()
        {
            if (PublicVar.SeiBei == SeiBeiClass.baoxun)
            {
                scan = new Scan();
                scan.RegisterHotKey();
                scan.Process += new ProcessDelegate(Scan_Process);
            }
            else if (PublicVar.SeiBei == SeiBeiClass.xindalu)
            {
                scanTest = new NLSScanner();
                scanTest.OnDecodeEvent += new DecodeEventHandler(scan_OnDecodeEvent);
                scanTest.Open();
                // scanTest.StartScan(true);
                MovFormControl();
                
            }
            else if (PublicVar.SeiBei == SeiBeiClass.AutoIDOne)
            {
                this.ScannerReader = new ScannerMsgOne(this);

                if (ScannerMsgOne.SSI_Register((IntPtr)ScannerReader.Hwnd, (uint)ScannerMsgOne.WM_READMSG)) // 初始条码扫描设备
                {
                    //可读扫描数据的事件
                    ScannerReader.OnScannerReader += new ScannerMsgOne.ScannerReader(this.ScanReader);
                }
                MovFormControl();
            }
            else if (PublicVar.SeiBei == SeiBeiClass.AutoID)
            {
                
                //ScannerMsg.ResCode resCode;
                //resCode = ScannerMsg.oemConnect();
                //if (resCode != ScannerMsg.ResCode.RESULT_SUCCESS)
                //{
                //    MessageBox.Show("oemConnect failed", "提示");
                //    return;
                //}

                //resCode = ScannerMsg.oemEnableSymbologyAll();
                //if (resCode != ScannerMsg.ResCode.RESULT_SUCCESS)
                //{
                //    MessageBox.Show("oemEnableSymbologyAll failed", "提示");
                //    return;
                //}
                //ScannerMsg.oemSetDecodeMode(ScannerMsg.SetupType.SETUP_TYPE_CURRENT, '1');

                //scanner2D = new ScanKey();
                //scanner2D.OnScannerDown += new ScanKey.ScanneKeyDown(scanner2D_OnScannerDown);
                //scanner2D.OnScannerUp += new ScanKey.ScanneKeyUp(scanner2D_OnScannerUp);

                //formOpenFlag = true;
                //threadStart = new ThreadStart(DoWork);
                //thread = new Thread(threadStart);
                //thread.Start();

                SCAN.Scanner2D.Scanner.Instance().OnScanedEvent += new Action<SCAN.Scanner2D.Scanner.CodeInfo>(scanner_OnScanedEvent);
                SCAN.Scanner2D.Scanner.Enable();

                MovFormControl();
            }
            else
            {
                this.cmh = new CustomMessageHandler(this);
                if (!cmh.InitScan())
                {
                    MessageBox.Show("初始化设备失败！");
                    return;
                }

                cmh.OnBarCodeNotify += new CustomMessageHandler.abc(this.OnBarCodeNotify);

                cmh.EnableBeeper(true);
                cmh.EnableVibrater(true);

                MovFormControl();

            }
        }

        void scanner_OnScanedEvent(SCAN.Scanner2D.Scanner.CodeInfo obj)
        {
            if (this.InvokeRequired)
            {
                Action<SCAN.Scanner2D.Scanner.CodeInfo> delegateFun = new Action<SCAN.Scanner2D.Scanner.CodeInfo>(scanner_OnScanedEvent);
                this.Invoke(delegateFun, obj);
            }
            else
            {
                AppendMessage(obj.barcode);
            }
        }

        private void AddtextBox3(string text)
        {
            if (textBox3.InvokeRequired)
            {
                UIDelegateMethodAddtextBox3 ui = new UIDelegateMethodAddtextBox3(AddtextBox3);
                textBox3.Invoke(ui, new object[] { text });
            }
            else
            {
                textBox3.Text = text;
            }
        }

        private void AddListBox(string value)
        {


            if (listBox1.InvokeRequired)
            {
                UIDelegateMethodAddListBox ui = new UIDelegateMethodAddListBox(AddListBox);
                listBox1.Invoke(ui, new object[] { value });
            }
            else
            {
                if (PublicVar.IsAutoAddWlCode)
                {
                    value = PublicVar.autoAddWlCode + value;
                }
                if (!string.IsNullOrEmpty(PublicVar.InterceptStr))
                {
                    if (value.IndexOf("JGW") >= 0)
                    {
                        value = value.Substring(value.IndexOf("-")+1, value.Length - value.IndexOf("-")-1);
                    }
                }

                listBox1.Items.Add(value);
            }
        }

        private void UpdateListBox(int i)
        {
            if (listBox1.InvokeRequired)
            {
                UIDelegateMethodListBox ui = new UIDelegateMethodListBox(UpdateListBox);
                listBox1.Invoke(ui, new object[] { i });
            }
            else
            {
                listBox1.Items.RemoveAt(i);
            }
        }

        /// <summary>
        /// 更新UI控件内容
        /// </summary>
        /// <param name="text"></param>
        private void UpdateUi(string text)
        {
            if (textBox1.InvokeRequired)
            {
                UIDelegateMethod ui = new UIDelegateMethod(UpdateUi);
                textBox1.Invoke(ui, new object[] { text });
            }
            else
            {
                textBox1.Text = text;
            }
        }

        private void UpdateUiLabel4(string text)
        {
            if (label4.InvokeRequired)
            {
                UIDelegateMethodLabel4 ui = new UIDelegateMethodLabel4(UpdateUiLabel4);
                label4.Invoke(ui, new object[] { text });
            }
            else
            {
                label4.Text = text;
            }
        }

        private void scan_OnDecodeEvent(object sender, NLSCAN.MacCtrl.ScannerEventArgs e)
        {
            try
            {
                if (listBox1.Focused)
                {
                    if (e.Data.Length >= 12)
                    {
                        if (PublicVar.IsCheckDistinct) //检查扫描的是否有重复值
                        {
                            allwlcode.Add(e.Data);
                            foreach (string atm in allwlcode)
                            {
                                if (string.Equals(atm, e.Data))
                                {
                                    MessageBox.Show(string.Format("{0}物流码已被扫描处理过，请谨慎操作！", e.Data));
                                    break;
                                }
                            }

                        }

                        this.listBox1.Items.Add(e.Data);
                        this.listBox1.Refresh();
                    }
                }

                if (textBox3.Focused)
                {
                    textBox3.Text = textBox3.Text + ";" + e.Data;
                    PublicVar.BeiZhu = textBox3.Text;
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void OnBarCodeNotify(byte[] BarCodeData, int nLength)
        {
            try
            {
                string BarCode = Encoding.Default.GetString(BarCodeData, 0, nLength);
                if (listBox1.Focused)
                {
                    if (BarCode.Length >= 12)
                    {
                        if (PublicVar.IsCheckDistinct) //检查扫描的是否有重复值
                        {
                            allwlcode.Add(BarCode);
                            foreach (string atm in allwlcode)
                            {
                                if (string.Equals(atm, BarCode))
                                {
                                    MessageBox.Show(string.Format("{0}物流码已被扫描处理过，请谨慎操作！", BarCode));
                                    break;
                                }
                            }

                        }

                        this.listBox1.Items.Add(BarCode);
                        this.listBox1.Refresh();
                    }
                }

                if (textBox3.Focused)
                {
                    textBox3.Text = textBox3.Text + ";" + BarCode;
                    PublicVar.BeiZhu = textBox3.Text;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Scan_Process(object sender, ProcessEventArgs e)
        {
            try
            {
                if (listBox1.Focused)
                {
                    if (e.Barcode.Length >= 12)
                    {
                        if (PublicVar.IsCheckDistinct) //检查扫描的是否有重复值
                        {
                            allwlcode.Add(e.Barcode);
                            foreach (string atm in allwlcode)
                            {
                                if (string.Equals(atm, e.Barcode))
                                {
                                    MessageBox.Show(string.Format("{0}物流码已被扫描处理过，请谨慎操作！", e.Barcode));
                                    break;
                                }
                            }

                        }

                        this.listBox1.Items.Add(e.Barcode);
                        this.listBox1.Refresh();
                    }
                }

                if (textBox3.Focused)
                {
                    textBox3.Text = textBox3.Text + ";" + e.Barcode;
                    PublicVar.BeiZhu = textBox3.Text;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //收到扫描结果的消息
        public void ScanReader(object sender, EventArgs e)
        {
            ScannerMsgOne.BARCODE BarCode = new ScannerMsgOne.BARCODE();

            if (ScannerMsgOne.SSI_GetData(ref BarCode))
            {
                //扫描成功发声音
                ScannerMsgOne.SSI_ReadOK((uint)ScannerMsgOne.ScannerOK.SoundRemind);

                // 获取条码类型名称
                StringBuilder buffer = new StringBuilder();
                buffer.Length = 64;
                ScannerMsgOne.SSI_GetBarcodeName(buffer, buffer.Length);

                // 清除本次扫描的条码
                ScannerMsgOne.SSI_ResetData();

                if (listBox1.Focused)
                {
                    if (BarCode.len >= 12)
                    {
                        if (PublicVar.IsCheckDistinct) //检查扫描的是否有重复值
                        {
                            allwlcode.Add(BarCode.code);
                            foreach (string atm in allwlcode)
                            {
                                if (string.Equals(atm, BarCode.code))
                                {
                                    MessageBox.Show(string.Format("{0}物流码已被扫描处理过，请谨慎操作！", BarCode.code));
                                    break;
                                }
                            }

                        }

                        this.listBox1.Items.Add(BarCode.code);
                        this.listBox1.Refresh();
                    }
                }

                if (textBox3.Focused)
                {
                    textBox3.Text = textBox3.Text + ";" + BarCode.code;
                    PublicVar.BeiZhu = textBox3.Text;
                }

                // 如果需要连续扫描，延时一段时间后，可以启动下一次扫描。
                // 如果不需要连续扫描，则这段代码不需要。
                // Thread.Sleep(500);
                // ScannerMsg.SSI_StartScan();
            }
        }

        #endregion

        /// <summary>
        /// 通过与WebServices交互，处理数据
        /// </summary>
        protected void StartDataSend()
        {
            while (true)
            {
                if (listBox1.Items.Count > 0)
                {
                    string strReturn = "";
                    string wlCode = listBox1.Items[0].ToString().TrimEnd('\0');

                    if (IsXiang)
                    {
                        if (_operationClass == OperationClass.ruku)
                        {
                            
                                strReturn = wlmanger.CartonDepositing(PublicVar.cpId,
                                                       PublicVar.cpMc,
                                                       PublicVar.kfId,
                                                       PublicVar.kfMc,
                                                       "",
                                                       "",
                                                       PublicVar.Ph,
                                                       PublicVar.UserId,
                                                       PublicVar.BeiZhu,
                                                       wlCode);
                        }
                        else if (_operationClass == OperationClass.cuku)
                        {
                            if (PublicVar.UserJxsDj > 0)
                            {
                                strReturn = wlmanger.Jxs_CartonPools(PublicVar.JxsId, PublicVar.JxsMc, PublicVar.Ph, PublicVar.UserId, PublicVar.BeiZhu, wlCode);
                            }
                            else
                            {
                                strReturn = wlmanger.CartonPools(PublicVar.JxsId,
                                                       PublicVar.JxsMc,
                                                       PublicVar.cpId,
                                                       PublicVar.cpMc,
                                                       PublicVar.Ph,
                                                       PublicVar.UserId,
                                                       PublicVar.BeiZhu,
                                                       wlCode);
                            }
                        }
                        else if (_operationClass == OperationClass.tuihuo)
                        {
                            if (PublicVar.UserJxsDj > 0)
                            {
                                strReturn = wlmanger.Jxs_CartonReturn(PublicVar.UserIngJxsCode, PublicVar.UserIngJxsName, PublicVar.UserId, PublicVar.BeiZhu, wlCode);
                            }
                            else
                            {
                                strReturn = wlmanger.CartonReturn(PublicVar.kfId,
                                                                  PublicVar.kfMc,
                                                                  PublicVar.UserId,
                                                                  PublicVar.BeiZhu,
                                                                  DateTime.Now.ToString(),
                                                                  wlCode);
                            }
                        }
                    }
                    else
                    {
                        if (_operationClass == OperationClass.ruku)
                        {
                            strReturn = wlmanger.SigleDepositing(PublicVar.cpId,
                                                   PublicVar.cpMc,
                                                   PublicVar.kfId,
                                                   PublicVar.kfMc,
                                                   "",
                                                   "",
                                                   PublicVar.Ph,
                                                   PublicVar.UserId,
                                                   PublicVar.BeiZhu,
                                                   wlCode);
                        }
                        else if (_operationClass == OperationClass.cuku)
                        {
                            if (PublicVar.UserJxsDj > 0)
                            {
                                strReturn = wlmanger.Jxs_SiglePools(PublicVar.JxsId, PublicVar.JxsMc, PublicVar.Ph, PublicVar.UserId, PublicVar.BeiZhu, wlCode);
                            }
                            else
                            {
                                strReturn = wlmanger.SiglePools(PublicVar.JxsId,
                                                        PublicVar.JxsMc,
                                                        PublicVar.cpId,
                                                        PublicVar.cpMc,
                                                        PublicVar.Ph,
                                                        PublicVar.UserId,
                                                        PublicVar.BeiZhu,
                                                        wlCode);
                            }
                        }
                        else if (_operationClass == OperationClass.tuihuo)
                        {
                            if (PublicVar.UserJxsDj > 0)
                            {
                                strReturn = wlmanger.Jxs_SigleReturn(PublicVar.UserIngJxsCode, PublicVar.UserIngJxsName, PublicVar.UserId, PublicVar.BeiZhu, wlCode);
                            }
                            else
                            {
                                strReturn = wlmanger.SigleReturn(PublicVar.kfId,
                                                                  PublicVar.kfMc,
                                                                  PublicVar.UserId,
                                                                  PublicVar.BeiZhu,
                                                                  DateTime.Now.ToString(),
                                                                  wlCode);
                            }
                        }
                    }

                    if (strReturn == "1")
                    {
                        //发送短信
                        if (OperationClass.cuku == _operationClass)
                        {
                            if (smsJxsid != PublicVar.JxsId)
                            {
                                string[] al = new string[1];
                                al[0] = PublicVar.JxsId;
                                wlmanger.SendSmS(al, 1, PublicVar.COMNAME + " 于 " + DateTime.Now.ToString() + " 给您发货，请注意查收！", PublicVar.COMID, PublicVar.COMID);
                                smsJxsid = PublicVar.JxsId;
                            }
                        }

                        log.Add(string.Format("物流码:{0}，操作方式:{1}，成功", wlCode, _operationClass.ToString()));

                        UpdateUi("操作成功");
                        UpdateListBox(0);
                        truesum++;
                    }
                    else
                    {
                        log.Insert(0, string.Format("物流码:{0}，操作方式:{1}，失败,失败原因:{2}", wlCode, _operationClass.ToString(), strReturn));

                        UpdateUi(strReturn);
                        UpdateListBox(0);
                        truesum++;
                        falsesum++;
                    }

                    //更新界面汇总信息
                    UpdateUiLabel4(string.Format("执行{0}个,{1}个错误", truesum.ToString(), falsesum.ToString()));
                }
                else
                {
                    Thread.Sleep(3000);

                    if ((truesum > 0) && ((truesum - ingwritesum) > 10))
                    {
                        if (string.IsNullOrEmpty(filepath))
                        {
                            filepath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\错误日志\" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.TimeOfDay.Hours.ToString() + DateTime.Now.TimeOfDay.Minutes.ToString() + ".txt";
                        }

                        using (StreamWriter sw = new StreamWriter(filepath, false, Encoding.GetEncoding("GB2312")))
                        {
                            sw.WriteLine(string.Format("执行{0}个,{1}个错误", truesum.ToString(), falsesum.ToString()));
                            for (int i = 0; i < log.Count; i++)
                            {
                                sw.WriteLine(log[i]);
                            }
                        }

                        ingwritesum = truesum;
                    }
                }
            }
        }


        public frmWl(OperationClass _operationClassvalue)
        {
            InitializeComponent();

            allwlcode = new List<string>();
            _operationClass = _operationClassvalue;
            wlmanger = new global::Scan.flManage.WlManger();
            wlmanger.Url = PublicVar.WLURL;

            if (_operationClass == OperationClass.ruku)
            {
                this.Text = "入库";
                this.radioButton1.Text = "整箱入库";
                this.radioButton2.Text = "单标入库";
                this.label2.Text = "入库编码：";
                this.menuItem6.Text = "设置入库编码";
                
            }
            else if (_operationClass == OperationClass.cuku)
            {
                this.Text = "出库";
                this.radioButton1.Text = "整箱出库";
                this.radioButton2.Text = "单标出库";
                this.label2.Text = "出库编码：";
                this.menuItem6.Text = "设置出库编码";
            }
            else if (_operationClass == OperationClass.tuihuo)
            {
                this.Text = "退货";
                this.radioButton1.Text = "整箱退货";
                this.radioButton2.Text = "单标退货";
                this.label2.Text = "退货编码：";
                this.menuItem6.Text = "设置退货编码";
            }

            InitScan();
        }

        private void menuItem6_Click(object sender, EventArgs e)
        {
            string atmp = string.Empty;

            if (_operationClass == OperationClass.ruku)
            {
                atmp = PublicVar.RuKuBm;

                frmSetBm fsb = new frmSetBm(_operationClass);
                fsb.ShowDialog();

                //if (atmp != PublicVar.RuKuBm)
               // {
                    textBox2.Text = PublicVar.RuKuBm;
               // }
            }

            if (_operationClass == OperationClass.cuku)
            {
                atmp = PublicVar.CuKuBm;

                frmSetBm fsb = new frmSetBm(_operationClass);
                fsb.ShowDialog();

              //  if (atmp != PublicVar.CuKuBm)
              //  {
                    textBox2.Text = PublicVar.CuKuBm;
              //  }
            }

            if (_operationClass == OperationClass.tuihuo)
            {
                atmp = PublicVar.TuiHuoBm;

                frmSetBm fsb = new frmSetBm(_operationClass);
                fsb.ShowDialog();
              //  if (atmp != PublicVar.TuiHuoBm)
              //  {
                    textBox2.Text = PublicVar.TuiHuoBm;
              //  }
            }
        }

        private void menuItem5_Click(object sender, EventArgs e)
        {
            if (listBox1.Items.Count > 0)
            {
                MessageBox.Show("还有任务未处理完，不能退出！");
                return;
            }

            if (isThreadRun)
            {
                DataThread.Abort();
            }
            this.Close();
        }

        private void menuItem1_Click(object sender, EventArgs e)
        {
            if ((!radioButton1.Checked) && (!radioButton2.Checked))
            {
                MessageBox.Show("请选择一个处理类型[单标还是箱标]！");
                return;
            }

            if (string.IsNullOrEmpty(textBox2.Text))
            {
                MessageBox.Show("请设置操作编码！");
                return;
            }

            if (listBox1.Items.Count <= 0)
            {
                MessageBox.Show("请执少得先扫描一个物流码再进行处理！");
                return;
            }

            PublicVar.BeiZhu = textBox3.Text;
            PublicVar.Ph = textBox4.Text;
            radioButton1.Enabled = false;
            radioButton2.Enabled = false;

            if (radioButton1.Checked)
            {
                IsXiang = true;
            }
            if (radioButton2.Checked)
            {
                IsDan = true;
            }

            if (PublicVar.IsThreadAutoRun == false)
            {
                StartDataSend();
            }
            else
            {
                if (isThreadRun == false)
                {
                    DataThread = new Thread(new ThreadStart(StartDataSend));
                    DataThread.IsBackground = true;
                    isThreadRun = true;
                    DataThread.Start();
                }
            }

        }

        private void frmWl_Load(object sender, EventArgs e)
        {
            if (PublicVar.IsThreadAutoRun == false)
            {
                this.menuItem1.Text = "处理";
            }
            else
            {
                this.menuItem1.Text = "开始后台处理";
            }
        }

        private void frmWl_Closing(object sender, CancelEventArgs e)
        {
            if (isThreadRun)
            {
                DataThread.Abort();
            }

            if (PublicVar.SeiBei == SeiBeiClass.baoxun)
            {
                scan.DisposeCallBack();
            }
            else if (PublicVar.SeiBei == SeiBeiClass.xindalu)
            {
                scanTest.StartScan(false);
                scanTest.Close();
            }
            else if (PublicVar.SeiBei == SeiBeiClass.AutoIDOne)
            {
                ScannerMsgOne.SSI_StopScan();
                ScannerMsgOne.SSI_Unregister((IntPtr)ScannerReader.Hwnd, (uint)ScannerMsgOne.WM_READMSG);
            }
            else if (PublicVar.SeiBei == SeiBeiClass.AutoID)
            {

                //scanner2D.stopListen();
                //isCanScanner = false;
                //formOpenFlag = false;

                SCAN.Scanner2D.Scanner.Instance().OnScanedEvent -= new Action<SCAN.Scanner2D.Scanner.CodeInfo>(scanner_OnScanedEvent);
                SCAN.Scanner2D.Scanner.Disable();

            }
            else
            {
                cmh.CloseBarCode();
            }

            //在这里写入错误日志
            if ((truesum > 0) && (truesum > ingwritesum))
            {
                if (string.IsNullOrEmpty(filepath))
                {
                    filepath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\错误日志\" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.TimeOfDay.Hours.ToString() + DateTime.Now.TimeOfDay.Minutes.ToString() + ".txt";
                }

                using (StreamWriter sw = new StreamWriter(filepath, false))
                {
                    sw.WriteLine(string.Format("执行{0}个,{1}个错误", truesum.ToString(), falsesum.ToString()));
                    for (int i = 0; i < log.Count; i++)
                    {
                        sw.WriteLine(log[i]);
                    }
                }

                ingwritesum = truesum;
            }


        }

       
        private void menuItem4_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder ();
            sb.Append(PublicVar.StrBanBen);
            sb.Append("\r\n");
            sb.Append(PublicVar.StrRiQi);
            MessageBox.Show(sb.ToString());
        }

        private void menuItem7_Click(object sender, EventArgs e)
        {
            if ((falsesum <= 0) || (string.IsNullOrEmpty(filepath)))
            {
                MessageBox.Show("没有错误日志");
                return;
            }

            if (File.Exists(filepath))
            {
                try
                {
                    System.Diagnostics.Process.Start(filepath, "");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                MessageBox.Show("没有找到日志");
            }
        }

        private void menuItem8_Click(object sender, EventArgs e)
        {
            frmSelectSb fss = new frmSelectSb(2);
            fss.ShowDialog();
        }

        private void menuItem9_Click(object sender, EventArgs e)
        {
            try
            {
                listBox1.Items.Remove(listBox1.SelectedItem);
                MessageBox.Show("删除成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void menuItem8_Click_1(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox2.Text))
            {
                if (radioButton1.Checked)
                {
                    IsXiang = true;
                }
                if (radioButton2.Checked)
                {
                    IsDan = true;
                }

                frmSetHandInput fshi = new frmSetHandInput(textBox3.Text, _operationClass, IsXiang, IsDan);
                fshi.ShowDialog();
            }
            else
            {
                MessageBox.Show("请先选择操作编码！");
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void listBox1_GotFocus(object sender, EventArgs e)
        {
            listBoxFocus = true;
        }

        private void listBox1_LostFocus(object sender, EventArgs e)
        {
            listBoxFocus = false;
        }

        private void textBox3_GotFocus(object sender, EventArgs e)
        {
            textBoxFocus = true;
        }

        private void textBox3_LostFocus(object sender, EventArgs e)
        {
            textBoxFocus = false;
        }

        private void label3_ParentChanged(object sender, EventArgs e)
        {

        }

      
    }
}